<script lang="ts" setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import 'element-plus/dist/index.css'
import SearchCom from '@/components/SearchCom.vue'
import {getDepartment, getDepartmentById, addDepartment, updateDepartment, deleteDepartment} from '@/api/school-api'

// 接口
interface CrpDepartment {
  id: number
  name: string,
  departmentAdminStudentId: string,
  departmentAdminStudentName: string,
}

// 声明变量
const dialogFormVisible = ref(false)
const isAddMode = ref(true)
const form = ref({
  id: '',
  name: '',
  departmentAdminStudentId: '',
})
// 搜索
const searchText = ref('')
const curPage = ref(1)
const total = ref(0)
// 表格
const tableData = ref([])


// 更新数据
const loadData = async () => {
  const { data } = await getDepartment(curPage.value, 10, searchText.value)

  tableData.value = data.list
  total.value = data.total
}
loadData()

// 搜索和添加按钮
const handleSearch = async (text: string) => {
  searchText.value = text
  // 获取表单数据并发送请求
  loadData()
}

const toAdd = () => {
  isAddMode.value = true
  dialogFormVisible.value = true
}


const toEdit = async (index: number, row: CrpDepartment) => {
  const { data } = await getDepartmentById(row.id)

  console.log(data);
  
  
  form.value = {
    id: String(data.id),
    name: data.name,
    departmentAdminStudentId: data.departmentAdminStudentId,
  }
  isAddMode.value = false
  dialogFormVisible.value = true
}

const handleDelete = async (index: number, row: CrpDepartment) => {
  await deleteDepartment(row.id)
  loadData()
}



// 对话框
const dialogTitle = computed(() => {
  return isAddMode.value ? '添加部门' : '编辑部门'
})

// 重置表单
const resetForm = () => {
  form.value.id = ''
  form.value.name = ''
  form.value.departmentAdminStudentId = ''
}

const handleCancel = () => {
  dialogFormVisible.value = false
  resetForm()
}

const handleAdd = async () => {
  if (form.value.name.trim() === '') {
    ElMessage.error('部门名称不能为空')
    resetForm()
    return
  }

  // 获取表单数据并发送请求
  await addDepartment({
    name: form.value.name,
  })

  // 刷新表格数据
  loadData()
  // 重置表单数据
  resetForm()

  dialogFormVisible.value = false
}

const handleEdit = async () => {
    // 发送请求
    await updateDepartment({
    id: form.value.id,
    name: form.value.name,
    departmentAdminStudentId: form.value.departmentAdminStudentId,
  })
  // 刷新表格数据
  loadData()
  // 重置表单数据
  resetForm()
  dialogFormVisible.value = false
}


// 分页
const handlePagination = async (page: any, size: any) => {
  curPage.value = page
  loadData()
}


</script>


<template>
  <div class="wrap">
    <!-- 搜索和添加按钮 -->
    <SearchCom @add="toAdd" @search="handleSearch"></SearchCom>

    <!-- 表格 -->
    <el-table :data="tableData" style="width: 100%">

      <el-table-column label="ID" width="50">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column label="班级名称">
        <template #default="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>

      <el-table-column label="班级管理员">
        <template #default="scope">
          <template v-if="scope.row.departmentAdminStudentId">
            {{ scope.row.departmentAdminStudentName }}（{{ scope.row.departmentAdminStudentId }}）
          </template>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="toEdit(scope.$index, scope.row)">
            编辑
          </el-button>
          <el-popconfirm confirm-button-text="是" cancel-button-text="否" :icon="InfoFilled" icon-color="#626AEF"
            title="是否删除？" @confirm="handleDelete(scope.$index, scope.row)">
            <template #reference>
              <el-button size="small" type="danger">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>

    </el-table>

    <!-- 分页 -->
    <div class="paginationWrap">
      <el-pagination @change="handlePagination" background layout="prev, pager, next" :total="total" />
    </div>


    <!-- 对话框 -->
    <el-dialog v-model="dialogFormVisible" @close="handleCancel" :title="dialogTitle" width="500" modal>
      <div class="wrap">
        <el-form :model="form" label-width="130px" label-position="left" style="max-width: 300px">
          <el-form-item v-if="!isAddMode" label="ID：">
            <el-input v-model="form.id" disabled />
          </el-form-item>

          <el-form-item label="部门名称：">
            <el-input v-model="form.name" />
          </el-form-item>

          <el-form-item v-if="!isAddMode" label="部门管理员学号：">
            <el-input v-model="form.departmentAdminStudentId" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button v-if="isAddMode" type="primary" @click="handleAdd">
            添加
          </el-button>
          <el-button v-else type="primary" @click="handleEdit">
            更新
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.paginationWrap {
  padding: 50px;
}
</style>